package com.example.serenity.controller;

import cn.hutool.json.JSONObject;
import com.example.serenity.controller.model.Response;
import com.example.serenity.util.AffineTransImage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.UUID;

@RestController
@RequestMapping("/image")
public class imageController {
    @Value("${file.dir}")
    private String dir;
    @Value(("${file.ip}"))
    private String ip;

    /**
     * 上传图片
     */
    @PostMapping(path = "/upload",consumes = "multipart/form-data")
    public Response<?> upload(@RequestParam("file") MultipartFile image){
        if(image==null) return new Response<>("0","附件为空！");
        if(image.getSize()>10485760L){
            return new Response<>("0", "图片最大不超过10MB！");
        }
        String fileName = image.getOriginalFilename();
        if(null == fileName)
            return new Response<>("0", "图片没有名字！");
        int index = fileName.lastIndexOf(".");
        if(index==-1){
            return new Response<>("0", "找不到图片格式！");
        }
        String suffixName = fileName.substring(index).toLowerCase(Locale.ROOT);//后缀名
        ///给图片改名
        fileName = UUID.randomUUID() + suffixName;
        File dest = new File(dir + fileName);
        if(!dest.getParentFile().exists()){
            if(!dest.getParentFile().mkdirs())
                return new Response<>("0", "服务器保存图片失败:文件目录未创建");
        }
        try {
            image.transferTo(dest);
        }catch (IOException e){
            e.printStackTrace();
            return new Response<>("0", "服务器保存图片失败！");
        }

        JSONObject res = new JSONObject();
        res.putOnce("url", ip + "/file/" +fileName);
        if(image.getSize()>104857L)//大于100kb创建缩略图
        {
            //创建缩略图
            AffineTransImage.minImage(dir,fileName);
            res.putOnce("minUrl", ip + "/file/min_" +fileName);
        }else{
            res.putOnce("minUrl", ip + "/file/" +fileName);
        }

        return new Response<>(res);
    }
}
